import jiekou,{base_url_java} from './interface.js';
import http from './http';

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function (n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function checkmobile(phone){
	if((/^1[3456789]\d{9}$/.test(phone))){ 
		return false; 
	} 
	return true;
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		milliseconds = (milliseconds+"").length==10?milliseconds*1000:milliseconds;
		milliseconds = new Date().getTime()-milliseconds;
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	timeConvert:function(timestamp,num){//num:0 YYYY-MM-DD  num:1  YYYY-MM-DD hh:mm:ss // timestamp:时间戳 
	            timestamp = timestamp+'';
	            timestamp = timestamp.length==10?timestamp*1000:timestamp;
	            var date = new Date(timestamp);
	            var y = date.getFullYear();  
	            var m = date.getMonth() + 1;  
	            m = m < 10 ? ('0' + m) : m;  
	            var d = date.getDate();  
	            d = d < 10 ? ('0' + d) : d;  
	            var h = date.getHours();
	            h = h < 10 ? ('0' + h) : h;
	            var minute = date.getMinutes();
	            var second = date.getSeconds();
	            minute = minute < 10 ? ('0' + minute) : minute;  
	            second = second < 10 ? ('0' + second) : second; 
	            if(num==0){
	                return y + '-' + m + '-' + d;  
	            }else{
	                return y + '-' + m + '-' + d +' '+ h +':'+ minute +':' + second;  
	            }
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	},
	dateFormat:function(fmt, date) {
		let ret;
		const opt = {
			"Y+": date.getFullYear().toString(),        // 年
			"m+": (date.getMonth() + 1).toString(),     // 月
			"d+": date.getDate().toString(),            // 日
			"H+": date.getHours().toString(),           // 时
			"M+": date.getMinutes().toString(),         // 分
			"S+": date.getSeconds().toString()          // 秒
			// 有其他格式化字符需求可以继续添加，必须转化成字符串
		};
		for (let k in opt) {
			ret = new RegExp("(" + k + ")").exec(fmt);
			if (ret) {
				fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
			};
		};
		return fmt;
	},
};

function checkID(haoma){
	var id=/^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/
	if (id.test(haoma)){
		return true;
	}else{
		return false;
	}
}

function nuiAjax(url,params,success){
	console.log(url+"?"+JSON.stringify(params));
	uni.request({
			url: url, //仅为示例，并非真实接口地址。
			data: params,
	    success: (res) => {
	        console.log(res);
	        success(res.data);
	    },
		fail: () => {
			console.log("接口调用失败");
		}
	});
}

function goback(){
	uni.navigateBack({
	    delta: 1,
	    animationType: 'pop-out',
	    animationDuration: 200
	});
}

function toUrl(url){
	uni.navigateTo({
		url:url
	})
}

function uploadFile(url,success){
	uni.chooseImage({
		success: (chooseImageRes) => {
			var tempFilePaths = chooseImageRes.tempFilePaths;
			console.log(tempFilePaths);
			uni.uploadFile({
				url: url, //仅为示例，非真实的接口地址
				filePath: tempFilePaths[0],
				name: 'file',
				success: (res) => {
					console.log(JSON.stringify(res));
					var data = JSON.parse(res.data);
					if(data.result=="200"){
						// that.user.head=data.database;
						// that.user.http=data.http;
						console.log(success);
						success(data.database);
						
						// console.log(JSON.stringify(that.user));
					}
				}
			});
		},
		fail:function(){
			console.log("shibai");
		}
	});
}

function toUrlNoBack(url){
	uni.redirectTo({
		url:url
	})
}

const getDictObject = async function(dictType){
	let dictData = uni.getStorageSync("dictData");
	let obj = {};
	if(dictData[dictType]==undefined || dictData[dictType]==""){
		let arr =[];
		await http(jiekou.getDictTypeList,{dictType}, {
			hideLoading: true, // 默认 false
			hideMsg: true, // 默认 false
			method: 'POST' // 默认 POST
		}).then(res => {
			arr = res.data;
		}).catch(err => {
			console.error(err);
		})
		for (var i = 0; i < arr.length; i++) {
			obj[arr[i].dictValue] = arr[i].dictLabel;
		}
	}else{
		obj = dictData[dictType];
	}
	
	
	return obj;
}

module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	checkmobile:checkmobile,
	nuiAjax:nuiAjax,
	goback:goback,
	toUrl:toUrl,
	toUrlNoBack:toUrlNoBack,
	uploadFile:uploadFile,
	checkID:checkID,
	getDictObject
}
